require 'httparty'
require 'json'

module Pictaculous
	class Client
		include HTTParty
		base_uri 'http://pictaculous.com/api/1.0'

	  # Returns a color palette for a given image
	  # 
	  # Parameters :
	  # * path (String)
	  # 
	  # Returns :
	  # * colors (Array)
	  #
	  def color_palette_for_image(path)
	    body = {image: to_binary(path)}
	    
	    response = JSON.parse(self.class.post("/", :body => body))

	    if response['info']
	    	response['info']['colors']
	    elsif response['status'] == 'error'
	    	raise Pictaculous::Error.new(response['error'])	    
	    end

	  rescue Errno::ENOENT => e
	  	raise Pictaculous::Error.new "Image not found (path : #{path})"
	  rescue => e
	  	raise Pictaculous::Error.new e.message
	  end

	  private

	  	def to_binary(image)
	  		if image.kind_of?(String)
	  			File.open(image, "rb") { |f| f.read }
	  		else
	  			raise ArgumentError.new('Unsuported format type. Please use a string (path)')
	  		end
	  	end

	end	
end